<template>
  <div class="work-order-list">
    <CommonHeader title="生产入库" :is-show-back="false" class="header-top" />
    <section class="search-box">
      <div class="inner">
        <el-select v-model="formData.warehouseCode" placeholder="所有仓库" clearable ref="searchSelect" @change="onRefresh('init')">
          <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.warehouseName" :value="item.warehouseCode"></el-option>
        </el-select>
        <van-search placeholder="搜索" readonly @cancel="searchFlag = false" @click="searchFlag = !searchFlag" @click-right-icon.stop="clearSearchEvent">
          <template #right-icon>
            <div class="right-icon">
              <img src="@/assets/images/clear.png" alt="" />
            </div>
          </template>
        </van-search>
        <div class="btn-wrap" @click="$router.push('/productInventory/add')">新增</div>
      </div>
      <SearchForm ref="SearchForm" :search-flag="searchFlag" :searchForm="{orderNumber:formData.orderNumber}" @cancel="cancelSearchEvent" @confirm="confirmSearchEvent"></SearchForm>
    </section>
    <div style="display:flex">
      <van-tabs @click="changeTab" v-model="formData.state" color="#548AF1" style=" width: 100%;">
        <van-tab v-for="(tab, index) in tabs" :key="index" :name="tab.state" :title="tab.title"></van-tab>
      </van-tabs>
    </div>
    <CommonMain>
      <template>
        <van-pull-refresh v-model="refreshing" :disabled="isRefreshDisable" @refresh="onRefresh">
          <van-list v-if="contentList.length > 0" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
            <listItem v-for="(item, index) in contentList" :key="index" :item-obj="item"></listItem>
          </van-list>
          <div v-if="!loading && contentList.length == 0" class="no-data">暂无数据</div>
        </van-pull-refresh>
      </template>
    </CommonMain>
    <van-dialog v-model="changeStateDialog" title="确认" className="sure-dialog"  show-cancel-button confirmButtonColor="#3C76FF" @confirm="changeStateDialogConfirm">
      <div class="model-content">
        <div class="name" v-if="changeStateDialogData.state==1">是否完成入库单：</div>
        <div class="name" v-if="changeStateDialogData.state==0">是否生效入库单：</div>
        <div class="value">{{ changeStateDialogData.orderNumber }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="changeStateDialogConfirm">确认</van-button>
      </div>
    </van-dialog>
    <img src="@/assets/images/allocation/scan.png"  v-draggable  class="scan-img" @click="scanCodeEvent"/>
  </div>
</template>

<script>
import listItem from './listItem.vue'
import CommonHeader from '@/components/CommonHeader/index.vue'
import CommonMain from '@/components/CommonMain/index.vue'
import { productionSelect} from '@/api/allocation'
import { stateChange, getList ,getScanList ,scanCodeRuleGet,purchaseCheckInQuantity} from '@/api/inventory'
import { removeBarCodePurchaseStocks } from '@/api/purchase'
import Vue from 'vue'
import Toasts from '@/components/Toast'
import { Dialog,Toast ,Tab, Tabs } from 'vant'
Vue.use(Dialog);
Vue.use(Toast);
import SearchForm from './components/SearchForm.vue'
import { reqProductOrderList, reqWarehouseList, reqProductOrderStatusNum } from "@/api/cj_productInventory.js";
export default {
  components: {
    CommonHeader,
    CommonMain,
    listItem,
    SearchForm,
    Toasts,
    [Dialog.Component.name]: Dialog.Component,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
  },
  data () {
    return {
      loading: false,
      refreshing: false,
      finished: false,
      searchFlag: false,
      search: '',
      //   扫码提示弹框
      isShowConfirmDialog: false,
      // 滚动与下拉冲突
      scrollTop: 0,
      isRefreshDisable: false,
      isRequest:false,
      show: false,
      tabs: [{title:"全部",state:"0,1,2"},{title:"创建",state:'0'},{title:"生效",state:'1'},{title:"完成",state:'2'}],
      warehouseList:[],
      formData:{
        page:1,
        size:10,
        state:"1,2",  //状态 全部-1,2 生效-1 完成-2
        warehouseCode:"",
        orderNumber:"",
        planStartTime:"",
        planEndTime:"",
        totalPages:0,
        totalElements:0
      },
      contentList:[],
      changeStateDialog:false,
      changeStateDialogData:{
        id:"",
        orderNumber:"",
        state:"",
        stateName:"",
        changeState:"",
        changeStateName:""
      }
    }
  },
  watch: {
    scrollTop (newval) {
      console.log('scrollTop',newval);
      if (newval > 0) {
        this.isRefreshDisable = true
      } else {
        this.isRefreshDisable = false
      }
    }
  },
  created(){
    document.title = "生产入库";
  },
  mounted(){
    this.onRefresh("init");
    this.getWareHouseInfo();
    this.getProductInventoryStatusNum();
    // 扫码枪扫码
    const scanning_gun_enable = process.env.VUE_APP_BAR_CODE_SCANNING_GUN || false;
    if(scanning_gun_enable){
      window["ScanCodeMsg"] = (res) => {
        if (res) {
          console.log(res, "ScanCodeMsg这是首页，监听到扫码枪有结果了");
          this.scanCodeEvent2(res)
        }
      }
    }
  },
  methods: {
    //扫码枪扫码
    async scanCodeEvent2(res){
      try {
        // const res = await window.flutter_inappwebview.callHandler('qrCode');
        const isDevelopment = process.env.NODE_ENV === 'development';
        let code = "SCRK20250401077";
        try {
          if(!isDevelopment){
            code = res;
          }
          console.log('调用精致提供的扫码api',code);
        } catch (error) {
          Dialog.confirm({title:'提示',message:'当前设备不支持扫码',confirmButtonText:"确定",cancelButtonText:"取消"});
          console.log("调用精致提供的扫码api",error);
          return;
        }
        this.formData.orderNumber = code;
        this.onRefresh("search");
        console.log('调用精致提供的扫码api',res);
      } catch (error) {
        Toast({message: error.message,position: 'top'});
        console.log("调用精致提供的扫码api",error);
      }
    },
    //查询仓库信息
    getWareHouseInfo(){
      reqWarehouseList().then(response => {
        if(response.code === 200){
          this.warehouseList = response.data.map(e => {
            return {
              warehouseCode:e.warehouseCode,
              warehouseName:e.warehouseName,
              warehouseId:e.warehouseId,
              warehouseType:e.warehouseType
            }
          })
        }
        console.log('请求仓库列表信息',response);
      },error => {
        Dialog.confirm({title:'提示',message:'未获取到仓库列表信息，请重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
          this.getWareHouseInfo();
        })
        console.log('请求仓库列表信息',error);
      })
    },
    //获取生产入库单列表信息
    getProductInventoryList(){
      const { page,size,state,warehouseCode,orderNumber,planStartTime,planEndTime } = this.formData;
      this.loading = true;
      this.refreshing = true;
      const parameter = {page,size:size,states:state,warehouseCode,orderNumber,planStartTime,planEndTime};
      console.log(parameter);
      reqProductOrderList(parameter).then(response => {
        if(response.code === 200){
          const { content = [], totalPages = 0, totalElements = 0 } = response.data || {};
          content.forEach(item => {
            item.isToggle = true;
          })
          if(this.formData.page > 1){
            this.contentList = this.contentList.concat(content);
          } else {
            this.contentList = content;
          }
          this.formData.totalPages = totalPages;
          this.formData.totalElements = totalElements;

          if (totalElements <= this.contentList.length || content.length == 0 || content.length < parameter.size){
            this.finished = true;
          }
        }
        this.loading = false;
        this.refreshing = false;
        console.log('获取生产入库单列表',response);
      },error => {
        if(error.message && error.message === 'axios cancel request'){
          return;
        }
        this.loading = false;
        this.refreshing = false;
        console.log('获取生产入库单列表',error.message);
        Dialog.confirm({title:'提示',message:'未获取到生产入库单列表信息，请重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
          this.getProductInventoryList();
        })
      })
    },
    //下拉刷新
    async onRefresh(type='init'){
      console.log('执行下拉刷新');
      this.loading = true;
      this.finished = false;
      this.formData.page = 1;
      this.contentList = [];
      this.getProductInventoryList();
    },
    //加载更多
    async onLoad(){
      console.log('滚动到底部===>',this.formData);
      if(this.finished){
        return;
      }
      this.formData.page += 1;
      this.getProductInventoryList();
    },
    //Tab切换
    changeTab(state,title){
      console.log('tab切换===>',state,title);
      this.formData.state = state;
      this.onRefresh('tabChange');
    },
    //点击扫码
    async scanCodeEvent(){
      const isDevelopment = process.env.NODE_ENV === 'development';
      let code = "SCRK20250401077";
      try {
        if(!isDevelopment){
          code = await window.flutter_inappwebview.callHandler('qrCode');
        }
        console.log('调用精致提供的扫码api',code);
      } catch (error) {
        Dialog.confirm({title:'提示',message:'当前设备不支持扫码',confirmButtonText:"确定",cancelButtonText:"取消"});
        console.log("调用精致提供的扫码api",error);
        return;
      }
      this.formData.orderNumber = code;
      this.onRefresh("search");
    },
    cancelSearchEvent(value){
      this.formData.orderNumber = "";
      this.formData.planStartTime = "";
      this.formData.planEndTime = "";
      this.searchFlag = false;
      this.onRefresh("search");
    },
    confirmSearchEvent(value){
      const { orderNumber,planStartTime,planEndTime } = value;
      this.formData.orderNumber = orderNumber;
      this.formData.planStartTime = planStartTime ? planStartTime + " 00:00:00" : "";
      this.formData.planEndTime = planEndTime ? planEndTime + " 23:59:59" : "";
      this.searchFlag = false;
      this.onRefresh("search");
    },
    clearSearchEvent(){
      this.$refs.SearchForm.cancel();
    },
    changeStateDialogConfirm(){
      const { id,orderNumber,state,stateName } = this.changeStateDialogData;
      const parameter = {orderNumber, state};
      reqUpdateProductionMaterial(parameter).then(response => {
        if(response.code === 200){
          this.onRefresh();
        }
        console.log('请求更改某生产入库单状态',response);
      },error => {
        console.log('请求更改某生产入库单状态',error);
      })
    },
    getProductInventoryStatusNum(){
      reqProductOrderStatusNum().then(response => {
        if(response.code === 200 && response.data){
          const a = response.data['全部'] || 0;
          const b = response.data['生效'] || 0;
          const c = response.data['完成'] || 0;
          const d = response.data['创建'] || 0;
          this.tabs[0].title = `全部(${a})`;
          this.tabs[1].title = `创建(${d})`;
          this.tabs[2].title = `生效(${b})`;
          this.tabs[3].title = `完成(${c})`;
        }
        console.log('获取生产入库单状态数量',response);
      },error => {
        Dialog.confirm({title:'提示',message:'未获取到生产入库单状态数量信息，点击确定重试',confirmButtonText:"确定",cancelButtonText:"取消"}).then(confirm => {
          this.getProductInventoryStatusNum();
        })
        console.log('获取生产入库单状态数量',error);
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../assets/css/common.scss';
.right-icon {
  display: flex;
  align-items: center;
}
.scan-img{
  position: fixed;
  bottom: 1vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.work-order-list {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .search-box {
    // height: 46px;
    position: relative;
    .inner{
      font-size: 16px;
      color: #fff;
      padding: 8px 12px;
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      ::v-deep {
        .el-input--suffix {
          .el-input__inner {
            height: 33px;
            width: 110px;
            border: 1px solid #548af1;
            color: #548af1;
            font-size: 12px;
            font-family: Source Han Sans CN, Source Han Sans CN;
            font-weight: 500;
            color: #548af1;
            &::placeholder {
              color: #548af1;
            }
          }
          .el-input__icon {
            line-height: 33px;
            color: #548af1;
          }
        }
      }
    }
    .van-search {
      flex: 1;
      padding: 0px 15px 0 3px;
      // height: 32px;
      border-radius: 4px;
      border: 1px #DEDEDE solid;
      margin-left: 5px;
    }
    .van-search__content {
        background-color: #ffffff;
        height: 32px;
      .van-cell {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
    .btn-wrap{
      width: 62px;
      height: 32px;
      background: #548AF1;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 7px;
      font-size: 14px;
      color: #fff;
    }
    .scan-box {
      display: flex;
      align-items: center;
      img {
        width: 20px;
      }
    }
  }
  .van-pull-refresh {
    height: 100%;
    overflow: scroll;
    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }
    .van-list {
      height: 100%;
      // overflow: scroll;
    }
    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }
}
.sure-dialog{
  border-radius: 4px;
}
.model-content{
  padding: 25px 10px 20px 26px;
  .name{
    font-size: 14px;
    color: #666666;
  }
  .value{
    font-size: 16px;
    color: #548AF1;
    margin-top: 10px;
  }
}
.shaixuan{
      width: 80px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 0 4px;
      color: #646566;
      font-size: 14px;
      line-height: 20px;
      cursor: pointer;
      background: #fff;
}
</style>
